<template>
  <view class="chat">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="left" @click="handleBack">
        <uv-icon name="arrow-left" size="24" />
        <text class="nav-title">保存返回</text>
      </view>
      <view>{{ cardData.role_name }}</view>
      <view></view>
    </view>
    <scroll-view class="chatBox" scroll-y :scroll-top="scrollTop">
      <!-- 初始化场景 -->
      <ExpandText :text="defaultData.scenario || ''" />
      <view
        v-for="(item, index) in messages"
        :key="index"
        :class="['msg-item', item.isMine ? 'mine' : 'other']"
      >
        <view class="avatar">
          <image :src="!item.isMine ? cardData.role_pic : ''" />
        </view>
        <view class="msg-content">
          <view class="bubble" :class="item.isMine ? 'mine' : 'other'">
            {{ item.content }}
          </view>
        </view>
      </view>
    </scroll-view>

    <view class="bar">
      <view class="barInput">
        <input v-model="input" class="input" @confirm="send" @keydown.enter="send" />
        <svg class="icon" aria-hidden="true" @click="send">
          <use xlink:href="#icon-fasong" />
        </svg>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import { ChatMessage, useChatSSE } from "@/utils/useChatSSE";
import { onLoad } from "@dcloudio/uni-app";
import RoleAPI from "@/api/role";
import ExpandText from "./components/ExpandText.vue";
import { useCardsStore } from "@/store/index";
const cardsStore = useCardsStore();
const cardData = ref<any>(cardsStore.currentCard || {});
const defaultData = ref<any>({})

const messages = ref<ChatMessage[]>([]);
const input = ref("");
const scrollTop = ref(0);

onLoad(() => {
  RoleAPI.getDetails(cardData.value.role_id).then((res: any) => {
    defaultData.value = res.data
    messages.value.unshift({
      content: res.data.first_mes,
      done: true
    })
  })
});

const handleBack = () => {
  uni.navigateBack();
};

const chat = useChatSSE({
  url: "/chat/stream_chat", // 你的单接口
  onMsg: (msg) => {
    if (messages.value?.[messages.value.length - 1]?.done) {
      messages.value.push(msg);
    } else {
      messages.value[messages.value.length - 1].content += msg.content
    }
    if (msg.done) {
      messages.value[messages.value.length - 1].done = true
      nextTick(() => (scrollTop.value = messages.value.length * 999));
    }
  },
  onErr: console.error,
});

function send() {
  if (!input.value.trim()) return;
  chat.send({ question: input.value, role_id: cardData.value.role_id });
  input.value = "";
}

onUnmounted(() => chat.close());
</script>

<style scoped lang="scss">
.chat {
  display: flex;
  flex-direction: column;
  height: 100vh;
  color: $uni-text-color-inverse;
  .nav-bar {
    height: 2.75rem;
    display: flex;
    align-items: center;
    padding: 0 0.75rem;
    color: #fff;
    justify-content: center;
    position: relative;
    .left {
      display: flex;
      align-items: center;
      left: 0;
      position: absolute;
    }
  }
  .chatBox {
    padding: 0.5rem 0.5rem 1.25rem;
    box-sizing: border-box;
    overflow-y: auto;
    flex: 1;
    .msg-item {
      margin: 30rpx 0;
      display: flex;
      align-items: flex-start;

      &.mine {
        flex-direction: row-reverse;
      }

      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        background: #ccc;
        flex-shrink: 0;
        overflow: hidden;

        image {
          width: 100%;
          height: 100%;
          display: block;
        }
      }

      .msg-content {
        max-width: calc(98% - 100rpx);
        position: relative;
        .bubble {
          padding: 20rpx 24rpx;
          border-radius: 20rpx;
          word-break: break-all;
          line-height: 1.5;
          font-size: 30rpx;

          &.mine {
            border-bottom-right-radius: 0;
            background: #766ac8;
            margin-right: 20rpx;
          }

          &.other {
            background: #111827;
            border-bottom-left-radius: 0;
            margin-left: 20rpx;
          }
        }
      }
    }
  }
  .bar {
    display: flex;
    align-items: center;
    padding: 0.75rem 0;
    box-sizing: border-box;
    border-top: 1px solid $uni-text-color;
    .barInput {
      display: flex;
      align-items: center;
      margin: 0 1rem;
      height: 2.6rem;
      background-color: #212121;
      border-radius: 1rem;
      flex: 1;
      padding: 0 1rem;
      .input {
        flex: 1;
        color: $uni-text-color-inverse;
      }
      .icon {
        width: 1.5rem;
        height: 1.5rem;
        fill: #b44280;
      }
    }
  }
}
</style>